<template>
  <div class="inventory-container">
    <div class="page-header">
      <button class="back-button" @click="goToHome">
        <span class="icon-arrow-left"></span>
        返回首页
      </button>
      <h1>库存盘点</h1>
    </div>
    
    <div class="page-content">
      <!-- 统计卡片 -->
      <div class="stats-cards">
        <div class="stat-card">
          <div class="stat-title">总耗材种类</div>
          <div class="stat-value">{{ totalCategories }}</div>
          <div class="stat-desc">种</div>
        </div>
        <div class="stat-card">
          <div class="stat-title">库存总量</div>
          <div class="stat-value">{{ totalStock }}</div>
          <div class="stat-desc">件</div>
        </div>
        <div class="stat-card warning">
          <div class="stat-title">库存预警</div>
          <div class="stat-value">{{ warningItems.length }}</div>
          <div class="stat-desc">种</div>
        </div>
        <div class="stat-card">
          <div class="stat-title">本月盘点次数</div>
          <div class="stat-value">{{ monthlyChecks }}</div>
          <div class="stat-desc">次</div>
        </div>
      </div>
      
      <!-- 操作区 -->
      <div class="operation-area">
        <button class="start-check-btn" @click="startNewCheck">
          <span class="icon-check">✓</span> 开始新盘点
        </button>
        
        <div class="search-filter">
          <input 
            type="text" 
            v-model="searchKeyword" 
            placeholder="搜索耗材名称或规格..."
          >
          <select v-model="checkStatus" @change="filterItems">
            <option value="all">全部状态</option>
            <option value="normal">正常</option>
            <option value="warning">库存预警</option>
            <option value="zero">库存不足</option>
          </select>
        </div>
      </div>
      
      <!-- 库存列表 -->
      <div class="inventory-table-container">
        <table class="inventory-table">
          <thead>
            <tr>
              <th>ID</th>
              <th>耗材名称</th>
              <th>规格型号</th>
              <th>单位</th>
              <th>系统库存</th>
              <th v-if="isChecking">实际库存</th>
              <th v-if="isChecking">差异</th>
              <th>库存预警线</th>
              <th>状态</th>
              <th v-if="isChecking">操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredItems" :key="item.id" :class="getRowClass(item)">
              <td>{{ item.id }}</td>
              <td>{{ item.name }}</td>
              <td>{{ item.specification }}</td>
              <td>{{ item.unit }}</td>
              <td>{{ item.systemStock }}</td>
              <td v-if="isChecking">
                <input 
                  type="number" 
                  v-model="item.actualStock" 
                  min="0"
                  @input="calculateDiff(item)"
                >
              </td>
              <td v-if="isChecking" :class="item.diff !== 0 ? 'has-diff' : ''">
                {{ item.diff }}
              </td>
              <td>{{ item.warningLine }}</td>
              <td>
                <span class="status-tag" :class="getStatusClass(item)">
                  {{ getStatusText(item) }}
                </span>
              </td>
              <td v-if="isChecking">
                <button class="confirm-btn" @click="confirmItem(item)">确认</button>
              </td>
            </tr>
            <tr v-if="filteredItems.length === 0">
              <td :colspan="isChecking ? 10 : 7" class="no-data">暂无数据</td>
            </tr>
          </tbody>
        </table>
      </div>
      
      <!-- 盘点操作按钮 -->
      <div v-if="isChecking" class="check-actions">
        <button class="cancel-check-btn" @click="cancelCheck">取消盘点</button>
        <button class="complete-check-btn" @click="completeCheck">完成盘点</button>
      </div>
      
      <!-- 盘点历史 -->
      <div class="history-section">
        <h2>盘点历史记录</h2>
        <div class="history-list">
          <div class="history-item" v-for="record in checkHistory" :key="record.id">
            <div class="history-header">
              <div class="history-title">盘点单 #{{ record.id }}</div>
              <div class="history-date">{{ formatDate(record.date) }}</div>
            </div>
            <div class="history-details">
              <div class="history-stat">操作人: {{ record.operator }}</div>
              <div class="history-stat">盘点项数: {{ record.totalItems }}</div>
              <div class="history-stat">差异项数: {{ record.diffItems }}</div>
              <button class="view-history-btn" @click="viewHistoryDetail(record)">查看详情</button>
            </div>
          </div>
          <div v-if="checkHistory.length === 0" class="no-history">暂无盘点记录</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'InventoryCheck',
  data() {
    return {
      // 库存数据
      inventoryItems: [
        {
          id: 1,
          name: '打印机墨盒',
          specification: 'HP-12A',
          unit: '个',
          systemStock: 15,
          actualStock: 15,
          warningLine: 5,
          diff: 0,
          confirmed: false
        },
        {
          id: 2,
          name: '复印纸',
          specification: 'A4-70g',
          unit: '箱',
          systemStock: 30,
          actualStock: 30,
          warningLine: 10,
          diff: 0,
          confirmed: false
        },
        {
          id: 3,
          name: 'U盘',
          specification: '32GB',
          unit: '个',
          systemStock: 8,
          actualStock: 8,
          warningLine: 5,
          diff: 0,
          confirmed: false
        },
        {
          id: 4,
          name: '鼠标',
          specification: '无线',
          unit: '个',
          systemStock: 3,
          actualStock: 3,
          warningLine: 5,
          diff: 0,
          confirmed: false
        },
        {
          id: 5,
          name: '键盘',
          specification: '机械',
          unit: '个',
          systemStock: 0,
          actualStock: 0,
          warningLine: 3,
          diff: 0,
          confirmed: false
        }
      ],
      
      // 盘点状态
      isChecking: false,
      originalInventory: [],
      
      // 搜索筛选
      searchKeyword: '',
      checkStatus: 'all',
      
      // 盘点历史
      checkHistory: [
        {
          id: 101,
          date: '2023-04-15',
          operator: '张三',
          totalItems: 5,
          diffItems: 1,
          details: [
            { id: 1, name: '打印机墨盒', system: 14, actual: 15, diff: 1 },
            { id: 2, name: '复印纸', system: 30, actual: 30, diff: 0 },
            { id: 3, name: 'U盘', system: 8, actual: 8, diff: 0 },
            { id: 4, name: '鼠标', system: 4, actual: 3, diff: -1 },
            { id: 5, name: '键盘', system: 0, actual: 0, diff: 0 }
          ]
        },
        {
          id: 100,
          date: '2023-03-20',
          operator: '李四',
          totalItems: 5,
          diffItems: 0,
          details: [
            { id: 1, name: '打印机墨盒', system: 14, actual: 14, diff: 0 },
            { id: 2, name: '复印纸', system: 30, actual: 30, diff: 0 },
            { id: 3, name: 'U盘', system: 8, actual: 8, diff: 0 },
            { id: 4, name: '鼠标', system: 4, actual: 4, diff: 0 },
            { id: 5, name: '键盘', system: 0, actual: 0, diff: 0 }
          ]
        }
      ]
    };
  },
  computed: {
    totalCategories() {
      return this.inventoryItems.length;
    },
    totalStock() {
      return this.inventoryItems.reduce((sum, item) => sum + item.systemStock, 0);
    },
    warningItems() {
      return this.inventoryItems.filter(item => item.systemStock <= item.warningLine && item.systemStock > 0);
    },
    zeroStockItems() {
      return this.inventoryItems.filter(item => item.systemStock === 0);
    },
    monthlyChecks() {
      const currentMonth = new Date().getMonth();
      const currentYear = new Date().getFullYear();
      return this.checkHistory.filter(record => {
        const date = new Date(record.date);
        return date.getMonth() === currentMonth && date.getFullYear() === currentYear;
      }).length;
    },
    filteredItems() {
      let filtered = [...this.inventoryItems];
      
      // 搜索筛选
      if (this.searchKeyword) {
        filtered = filtered.filter(item => 
          item.name.includes(this.searchKeyword) || 
          item.specification.includes(this.searchKeyword)
        );
      }
      
      // 状态筛选
      if (this.checkStatus === 'normal') {
        filtered = filtered.filter(item => item.systemStock > item.warningLine);
      } else if (this.checkStatus === 'warning') {
        filtered = filtered.filter(item => item.systemStock <= item.warningLine && item.systemStock > 0);
      } else if (this.checkStatus === 'zero') {
        filtered = filtered.filter(item => item.systemStock === 0);
      }
      
      return filtered;
    }
  },
  methods: {
    goToHome() {
      this.$router.push('/home');
    },
    
    // 开始新盘点
    startNewCheck() {
      // 保存原始库存数据
      this.originalInventory = JSON.parse(JSON.stringify(this.inventoryItems));
      // 重置盘点数据
      this.inventoryItems.forEach(item => {
        item.actualStock = item.systemStock;
        item.diff = 0;
        item.confirmed = false;
      });
      this.isChecking = true;
    },
    
    // 取消盘点
    cancelCheck() {
      if (confirm('确定要取消当前盘点吗？所有已输入的数据将丢失。')) {
        this.inventoryItems = JSON.parse(JSON.stringify(this.originalInventory));
        this.isChecking = false;
      }
    },
    
    // 完成盘点
    completeCheck() {
      const unconfirmed = this.inventoryItems.some(item => !item.confirmed);
      if (unconfirmed && !confirm('存在未确认的盘点项，确定要完成盘点吗？')) {
        return;
      }
      
      // 计算差异项数
      const diffItems = this.inventoryItems.filter(item => item.diff !== 0).length;
      
      // 更新系统库存
      this.inventoryItems.forEach(item => {
        item.systemStock = item.actualStock;
      });
      
      // 记录盘点历史
      const newRecord = {
        id: Math.max(...this.checkHistory.map(r => r.id), 0) + 1,
        date: new Date().toISOString().split('T')[0],
        operator: '当前用户',
        totalItems: this.inventoryItems.length,
        diffItems: diffItems,
        details: this.inventoryItems.map(item => ({
          id: item.id,
          name: item.name,
          system: item.systemStock,
          actual: item.actualStock,
          diff: item.diff
        }))
      };
      
      this.checkHistory.unshift(newRecord);
      
      this.isChecking = false;
      alert(`盘点完成！共盘点 ${this.inventoryItems.length} 项，差异 ${diffItems} 项。`);
    },
    
    // 计算差异
    calculateDiff(item) {
      item.diff = item.actualStock - item.systemStock;
    },
    
    // 确认项目
    confirmItem(item) {
      item.confirmed = true;
    },
    
    // 筛选项目
    filterItems() {
      // 触发计算属性更新
    },
    
    // 获取行样式
    getRowClass(item) {
      return {
        'warning-row': item.systemStock <= item.warningLine && item.systemStock > 0,
        'zero-row': item.systemStock === 0,
        'confirmed-row': this.isChecking && item.confirmed
      };
    },
    
    // 获取状态文本
    getStatusText(item) {
      if (item.systemStock === 0) {
        return '库存不足';
      } else if (item.systemStock <= item.warningLine) {
        return '库存预警';
      } else {
        return '正常';
      }
    },
    
    // 获取状态样式
    getStatusClass(item) {
      if (item.systemStock === 0) {
        return 'status-zero';
      } else if (item.systemStock <= item.warningLine) {
        return 'status-warning';
      } else {
        return 'status-normal';
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      const date = new Date(dateString);
      return date.toLocaleDateString('zh-CN');
    },
    
    // 查看历史详情
    viewHistoryDetail(record) {
      let detailText = `盘点单 #${record.id}\n日期: ${this.formatDate(record.date)}\n操作人: ${record.operator}\n\n`;
      
      record.details.forEach(item => {
        detailText += `${item.name}: 系统 ${item.system} / 实际 ${item.actual} (${item.diff !== 0 ? '差异: ' + item.diff : '无差异'})\n`;
      });
      
      alert(detailText);
    }
  }
};
</script>

<style scoped>
.inventory-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e1e5e8;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 15px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 20px;
  font-weight: 500;
}

.back-button:hover {
  background: #2980b9;
  transform: translateY(-2px);
}

.icon-arrow-left::before {
  content: "←";
}

.stats-cards {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  flex-wrap: wrap;
}

.stat-card {
  flex: 1;
  min-width: 200px;
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s, box-shadow 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.stat-card.warning {
  border-left: 4px solid #f39c12;
}

.stat-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.stat-desc {
  color: #999;
  font-size: 13px;
}

.operation-area {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.start-check-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px 20px;
  background: #2ecc71;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
  font-weight: 500;
}

.start-check-btn:hover {
  background: #27ae60;
  transform: translateY(-2px);
}

.icon-check {
  font-weight: bold;
}

.search-filter {
  display: flex;
  gap: 10px;
  align-items: center;
}

.search-filter input,
.search-filter select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 14px;
}

.search-filter input {
  width: 300px;
}

.inventory-table-container {
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  margin-bottom: 20px;
}

.inventory-table {
  width: 100%;
  border-collapse: collapse;
}

.inventory-table th,
.inventory-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #f0f0f0;
}

.inventory-table th {
  background-color: #f9fafb;
  font-weight: 600;
  color: #333;
}

.inventory-table tr:hover {
  background-color: #f9fafb;
}

.warning-row {
  background-color: #fef5e7;
}

.zero-row {
  background-color: #fdedeb;
}

.confirmed-row {
  background-color: #eafaf1;
}

.status-tag {
  display: inline-block;
  padding: 3px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-normal {
  background-color: #eafaf1;
  color: #27ae60;
}

.status-warning {
  background-color: #fef5e7;
  color: #f39c12;
}

.status-zero {
  background-color: #fdedeb;
  color: #e74c3c;
}

.has-diff {
  color: #e74c3c;
  font-weight: bold;
}

.confirm-btn {
  padding: 4px 8px;
  background: #2ecc71;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background 0.3s;
  font-size: 13px;
}

.confirm-btn:hover {
  background: #27ae60;
}

.check-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-bottom: 30px;
}

.cancel-check-btn {
  padding: 10px 20px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 5px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-check-btn:hover {
  background: #f5f5f5;
}

.complete-check-btn {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  transition: background 0.3s;
}

.complete-check-btn:hover {
  background: #2980b9;
}

.no-data {
  text-align: center;
  color: #999;
  padding: 40px;
}

.history-section {
  margin-top: 30px;
}

.history-section h2 {
  color: #333;
  margin-bottom: 15px;
  font-size: 18px;
}

.history-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.history-item {
  background: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  transition: box-shadow 0.3s;
}

.history-item:hover {
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
}

.history-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #f0f0f0;
}

.history-title {
  font-weight: 600;
  color: #333;
}

.history-date {
  color: #666;
  font-size: 14px;
}

.history-details {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.history-stat {
  color: #666;
  font-size: 14px;
}

.view-history-btn {
  padding: 5px 10px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 3px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 13px;
}

.view-history-btn:hover {
  background: #2980b9;
}

.no-history {
  text-align: center;
  color: #999;
  padding: 30px;
  background: white;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}
</style>